﻿/*
 * Summary:
 *   This class wraps up a control and manages its layout
 *   by re-positioning and re-sizing of internal elements
 *   proportionately when the control is being resized.
 *   
 * History:
 *   Date           Author      Changes
 *   02/11/2010     YIWEI YU    Created
 */


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;


namespace AcmeSportsStore
{
    class LayoutController
    {
        protected class ControlNode
        {
            public Rectangle Rect;
            public Control Control;

            public ControlNode[] Subnodes;

            public ControlNode(Rectangle rect, Control control)
            {
                Rect = rect;
                Control = control;
            }
        }

        protected ControlNode mRoot;


        public LayoutController(Control control)
        {
            mRoot = TakeSnapshot(control);
        }

        public void UpdateAfterResizing()
        {
            UpdateAfterResizing(mRoot);
        }

        /*
         * TODO: comments to be added
         */
        protected ControlNode TakeSnapshot(Control control)
        {
            ControlNode node = new ControlNode(
                new Rectangle(control.Location, control.Size), control
                );

            int count = control.Controls.Count;
            node.Subnodes = new ControlNode[count];

            for (int i = 0; i < count; i++)
            {
                node.Subnodes[i] = TakeSnapshot(control.Controls[i]);
            }

            return node;
        }

        /*
         * TODO: comments to be added
         */
        protected void UpdateAfterResizing(ControlNode node)
        {
            Control control = node.Control;
            Size originalSize = node.Rect.Size;
            Size newSize = control.Size;

            foreach (ControlNode subnode in node.Subnodes)
            {
                int x = (subnode.Rect.Location.X *
                    newSize.Width + originalSize.Width / 2)
                    / originalSize.Width;
                int y = (subnode.Rect.Location.Y *
                    newSize.Height + originalSize.Height / 2)
                    / originalSize.Height;

                int w = (subnode.Rect.Size.Width *
                    newSize.Width + originalSize.Width / 2)
                    / originalSize.Width;
                int h = (subnode.Rect.Size.Height *
                    newSize.Height + originalSize.Height / 2)
                    / originalSize.Height;

                subnode.Control.Location = new Point(x, y);
                subnode.Control.Size = new Size(w, h);

                UpdateAfterResizing(subnode);
            }
        }
    }
}
